<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('clue.quick Search Fields') })"
        ></TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef"></Table>

        <el-dialog
                class="ba-operate-dialog select-db-dialog"
                v-model="state.dialog.visible"
                title="指派工程师"
                :destroy-on-close="true"
            >
                <el-form
                    :label-width="140"
                    @keyup.enter="onSubmit()"
                    class="select-db-form"
                    ref="formRef"
                >
                        <FormItem
                            label="工程师"
                            class="select-db"
                            type="select"
                            :key="JSON.stringify(state.dialog.dbList)"
                            v-model="state.dialog.workerId"
                            placeholder="选择工程师"
                            :data="{
                                content: state.dialog.dbList,
                            }"
                            :attr="{
                                blockHelp: '这里只能指派内部工程师进行处理',
                            }"
                            prop="workerId"
                        />              
                </el-form>
                <template #footer>
                    <div :style="{ width: 'calc(100% * 0.9)' }">
                        <el-button @click="state.dialog.visible = false">{{ $t('Cancel') }}</el-button>
                        <el-button :loading="state.loading" @click="onSubmit()" v-blur type="primary">{{ t('Confirm') }}</el-button>
                    </div>
                </template>
            </el-dialog>

        <!-- 表单 -->
        <PopupForm />
        <Info />
    </div>
</template>

<script setup lang="ts">
import { concat, cloneDeep } from 'lodash-es'
import { onMounted, provide, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import Info from './info.vue'
import baTableClass from '/@/utils/baTable'
import { buildJsonToElTreeData } from '/@/utils/common'
import { getWorkerList, assign } from '/@/api/backend/workorder'
import FormItem from '/@/components/formItem/index.vue'

defineOptions({
    name: 'clue',
})

const state = reactive({
    dialog: {
        clueId: 0,
        workerId: 0,
        visible: false,
        dbList: [],
        loading: false,
    },
    showLog: false,
    loading: false,
    successRecord: 0,
})

const { t } = useI18n()
const tableRef = ref()
//const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
let optButtons: OptButton[] = [
    {
        render: 'tipButton',
        name: 'info',
        title: 'Info',
        text: '',
        type: 'primary',
        icon: 'fa fa-search-plus',
        class: 'table-row-edit',
        disabledTip: false,
        click: (row: TableRow) => {
            infoButtonClick(row)
        },
    },
    {
        render: 'tipButton',
        name: 'info',
        title: '指派工程师',
        text: '',
        type: 'primary',
        icon: 'fa fa-check icon',
        class: 'table-row-edit',
        disabledTip: false,
        click: (row: TableRow) => {
            assignButtonClick(row)
        },
    },
    // {
    //     render: 'tipButton',
    //     name: 'info',
    //     title: 'Info',
    //     text: '',
    //     type: 'primary',
    //     icon: 'fa fa-sign-in icon',
    //     class: 'table-row-edit',
    //     disabledTip: false,
    //     click: (row: TableRow) => {
    //         infoButtonClick(row)
    //     },
    // },
]

optButtons = concat(optButtons, defaultOptButtons(['delete']))

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/Clue/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('clue.sn'), prop: 'sn', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false, width: 140 },
            { label: t('clue.title'), prop: 'title', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: '推送单位', prop: 'company.name', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', width: 200 },
            { label: '当前节点', prop: 'process', align: 'center', operator: 'RANGE', sortable: false, width: 120 },
            { label: '当前处理人', prop: 'processor', align: 'center', operator: 'RANGE', width: 120, sortable: false },
            { label: t('clue.status'), prop: 'status', align: 'center', render: 'tags', operator: 'LIKE', width: 100, sortable: false,
                custom: { '0': 'danger', '1': 'danger' , '2': 'danger', '3': 'success', '4': 'success', '5': 'success'},
                replaceValue: { '0': '待发送', '1': '已接收', '2': '进行中', '3': '挂起', '4': '结束', '5': '取消' },
            },
            { label: '推送时间', prop: 'create_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: '更新时间', prop: 'update_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('Operate'), align: 'center', width: 160, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: ['all', 'status'],
    },
    {
        defaultItems: { money: 0, deadline: null, status: '1' },
    }
)

provide('baTable', baTable)

/** 点击查看详情按钮响应 */
const infoButtonClick = (row: TableRow) => {
    if (!row) return
    // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
    let rowClone = cloneDeep(row)
    rowClone.data1 = rowClone.data1 ? [{ label: '点击展开', children: buildJsonToElTreeData(JSON.parse(rowClone.data1)) }] : []
    rowClone.data2 = rowClone.data2 ? [{ label: '点击展开', children: buildJsonToElTreeData(JSON.parse(rowClone.data2)) }] : []
    rowClone.data3 = rowClone.data3 ? [{ label: '点击展开', children: buildJsonToElTreeData(JSON.parse(rowClone.data3)) }] : []
    baTable.form.extend!['info'] = rowClone
    baTable.form.operate = 'Info'
}

/** 点击指派按钮响应 */
const assignButtonClick = (row: TableRow) => {
    if (!row) return
    // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
    state.successRecord = 1
    state.dialog.clueId = row.id
    getWorkerList().then((res) => {
        console.log(res.data);
        state.dialog.dbList = res.data
        state.dialog.visible = true
    })
}

// 提交指派工程师
const onSubmit = () => {
   
    state.dialog.loading = true
    assign({
        id: state.dialog.clueId,
        engineer: state.dialog.workerId
    })
        .then(() => {
            state.dialog.visible = false
            baTable.getIndex()
        })
        .finally(() => {
            state.dialog.loading = false
        })
}

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss">
:deep(.select-db-dialog) .el-dialog__body {
    height: unset;
    .select-db-form {
        width: 88%;
    }
    .success-record-alert {
        width: calc(100% - 140px);
        margin-left: 140px;
        margin-bottom: 30px;
        margin-top: -30px;
    }
}
.select-db {
    margin: 40px 0;
}
</style>
